//管理用户数据
import { defineStore } from 'pinia'
import { LoginAPI } from "@/apis/user.js";
import { ref } from 'vue';
import { useCartStore } from "./cartStore"
import { mergeCartAPI } from "@/apis/cart.js"
export const useUserStore = defineStore('user', () => {
    const cartStore = useCartStore()
    //1定义管理用户数据
    const userInfo = ref({});

    // 2 //定义获取接口数据
    const getUserInfo = async ({ account, password }) => {
        const res = await LoginAPI({ account, password });
        userInfo.value = res.result
        await mergeCartAPI(cartStore.cartList.map(item => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count: item.count
            }
        }))
        cartStore.updateNewList()
    }
    // clear清除token
    const clearUserInfo = () => {
        userInfo.value = {}
        //执行清除购物车的action
        cartStore.clearCart()
    }
    // 3一堆对象的格式导出
    return { userInfo, getUserInfo, clearUserInfo }
}, { persist: true } //让数据持久化
)